/**
 * @description expenseModel Service
 */

 const { expenseModel } = require('../db/index')
 const Op = require('sequelize').Op
 

 async function addData(params) {
   const result = await expenseModel.create(params)
   const data = result.dataValues
   return data
 }
 
 /**
  * 
  * @param {string} username 用户名 
  */
 async function getUserInfo(username) {
   // 查询条件
   const whereOption = {
    username
   }
   const result = await expenseModel.findOne({
     where: whereOption
   })
   if (result === null) {
     return result
   }
   return result.dataValues
 }
 
 /**
  * 修改用户信息
  * @param {*} param0 要修改的用户信息
  * @param {*} param1 查询条件
  */
 async function updateData(
   params,
   id
 ) {
   // 拼接修改内容
   const updateObj = params
 
   // 拼接查询条件
   const whereOption = {}
   if (id) {
     whereOption.id = id
   }
 
   // 执行修改
   const result = await expenseModel.update(updateObj, {
     where: whereOption
   })
   return result[0] > 0
 }
 
 /**
  * 删除用户
  * @param {string} userid 用户id 
  */
 async function deleteData(id) {
   const result = await expenseModel.destroy({
     where: {
       id
     }
   })
   return result > 0
 }
 
 /**
  * 分页查询所有用户
  * @param {number} page 当前页码
  * @param {number} pageSize 每页条数
  */
 async function queryAll({ page = 1, pageSize = 10, no, status, isDelete, title, creatorId }) {
   const whereOption = {
    isDelete
   }
   if (no) {
     whereOption.no = {
       [Op.like]: `%${no}%`
     }
   }
   if (title) {
     whereOption.title = {
       [Op.like]: `%${title}%`
     }
   }
   if (creatorId) {
    whereOption.creatorId = creatorId
   }
   if (status) {
    whereOption.status = status
   }
 
   if (page < 1) {
     page = 1
   }
   const result = await expenseModel.findAll({
     limit: pageSize,
     offset: (page - 1) * pageSize,
     where: whereOption
   })
   const total = await expenseModel.findAll()
   return {
     page,
     pageSize,
     total: total.length || 0,
     data: result || []
   }
 }

 async function destroyPkgFun() {
  const result = await expenseModel.findAll({
    where: {
      isDelete: 'true'
    }
  })
  for (let r of result) {
    if (new Date().getTime() - new Date(r.deleteTime).getTime() > 86400 * 1000 * 7) {
      const de = await expenseModel.destroy({
        where: {
          id: r.id
        }
      })
    }
  }
 }
 
 module.exports = {
  addData,
   getUserInfo,
   updateData,
   deleteData,
   queryAll,
   destroyPkgFun
 }
 